import { getCampusSelector, getTrainList } from '@/api/campus/campus'
import request from '@/utils/request'
import TeacherBox from '../TeacherBox/index.vue'
export default {
  components: { TeacherBox },
  props: [],
  data() {
    return {
      loading: false,
      visible: false,
      isDetail: false,
      teacherBoxVisible: false,
      dataForm: {
        trainId: undefined,
        campusId: undefined,
        // teacherId: [],
        teachers: []
      },
      rules: {
        trainId: [
          {
            required: true,
            message: '请选择师训',
            trigger: 'change'
          }
        ],
        campusId: [
          {
            required: true,
            message: '请选择校区',
            trigger: 'change'
          }
        ],
        teacherId: [
          {
            required: true,
            message: '请选择报名老师',
            trigger: 'change'
          }
        ],
        teachers: [
          {
            required: true,
            message: '请选择报名老师',
            trigger: 'change'
          }
        ]
      },
      genderOptions: [],
      brandOptions: [],
      campusOptions: [],
      trainOptions: [],
      teachers: [],
      campusLoading: false
    }
  },
  computed: {},
  watch: {},
  created() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'sex' }).then(res => {
      this.genderOptions = res
    })
  },
  mounted() {},
  methods: {
    async closeForm(data) {
      if (data.length > 0) {
        this.dataForm.teachers = this.dataForm.teachers.concat(data)
        this.dataForm.teachers = Array.from(new Set(this.dataForm.teachers.map(JSON.stringify)), JSON.parse)
      } else {
        this.$message({
          message: '请确认添加老师，否则订单不能创建',
          type: 'warning'
        })
      }
    },
    async loadCampusOptions(val) {
      try {
        this.campusLoading = true
        const query = { brand: val, fields: 'id,fullName' }
        const res = await getCampusSelector(query)
        const list = Array.isArray(res.data) ? res.data : []
        // 新建报名仅可选择筹备校区，编辑允许全部
        this.campusOptions = !this.dataForm.id ? list.filter(i => i.status == 'preparation') : list
      } catch (err) {
        console.error('加载校区下拉选项失败:', err)
        this.$message.error('校区选项加载失败')
        this.campusOptions = []
      } finally {
        this.campusLoading = false
      }
      // 同步加载师训列表
      try {
        const resTrain = await getTrainList({ brand: val })
        this.trainOptions = Array.isArray(resTrain.data) ? resTrain.data : []
      } catch (err) {
        console.error('加载师训列表失败:', err)
        this.$message.error('师训列表加载失败')
        this.trainOptions = []
      }
    },

    handleDelTrainOrderItemEntityList(index) {
      this.dataForm.teachers.splice(index, 1)
      /*this.dataForm.memo = this.dataForm.teachers
        .map(o => {
          return o.teacherName
        })
        .toString()*/
    },
    openTeacherBox() {
      if (!this.dataForm.campusId) {
        this.$message({
          message: '请先选择报名校区',
          type: 'error',
          duration: 1000
        })
        return
      } else if (!this.dataForm.trainId) {
        this.$message({
          message: '请先选择报名师训',
          type: 'error',
          duration: 1000
        })
        return
      } else {
        this.teacherBoxVisible = true
        this.$nextTick(() => {
          this.$refs.teacherBox.initData(this.dataForm.teachers)
        })
      }
    },
    goBack() {
      this.$emit('refresh')
    },
    init() {
      this.visible = true
      this.$nextTick(() => {
        this.$refs['elForm'].resetFields()
      })
    },
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          if (!this.dataForm.id) {
            request({
              url: `api/train/order/addrecord`,
              method: 'post',
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  ;(this.visible = false), this.$emit('refresh', true)
                }
              })
            })
          } /*else {
            request({
              url: '/api/campus/train/sign/' + this.dataForm.id,
              method: 'PUT',
              data: this.dataForm
            }).then((res) => {
              this.$message({
                message: res.msg,
                type: 'success',
                duration: 1000,
                onClose: () => {
                  this.visible = false
                  this.$emit('refresh', true)
                }
              })
            })
          }*/
        }
      })
    }
  }
}
